import React, { useState, useEffect } from 'react';
import {
  AppBar,
  Toolbar,
  Typography,
  Container,
  Box,
  CssBaseline,
  ThemeProvider,
  createTheme,
  Alert,
  Snackbar,
  Drawer,
  List,
  ListItem,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Divider,
  IconButton
} from '@mui/material';
import {
  Menu as MenuIcon,
  People as PeopleIcon,
  Dashboard as DashboardIcon,
  Folder as FolderIcon,
  Wallpaper as WallpaperIcon
} from '@mui/icons-material';
import { Routes, Route, Navigate, useNavigate, useLocation } from 'react-router-dom';
import LoginPage from './components/LoginPage';
import UserManagement from './components/UserManagement';
import FileManagement from './components/FileManagement';
import BackgroundConfig from './components/BackgroundConfig';
import { api, User } from '../request';

const theme = createTheme({
  palette: {
    primary: {
      main: '#1976d2',
    },
    secondary: {
      main: '#dc004e',
    },
  },
});



const drawerWidth = 240;

const AdminApp: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
  const [currentUser, setCurrentUser] = useState<User | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [notification, setNotification] = useState<{
    open: boolean;
    message: string;
    severity: 'success' | 'error' | 'warning' | 'info';
  }>({ open: false, message: '', severity: 'info' });

  const handleDrawerToggle = () => {
    setMobileOpen(!mobileOpen);
  };

  useEffect(() => {
    // 检查localStorage中的认证状态
    const savedUser = localStorage.getItem('adminUser');
    if (savedUser) {
      try {
        const user = JSON.parse(savedUser);
        setCurrentUser(user);
        setIsAuthenticated(true);
        setLoading(false);
        return;
      } catch (error) {
        localStorage.removeItem('adminUser');
      }
    }
    checkAuthStatus();
  }, []);

  const checkAuthStatus = async () => {
    try {
      const user = await api.admin.getCurrentUser();
      if (user) {
        setCurrentUser(user);
        setIsAuthenticated(true);
        localStorage.setItem('adminUser', JSON.stringify(user));
      } else {
        setIsAuthenticated(false);
        setCurrentUser(null);
        localStorage.removeItem('adminUser');
      }
    } catch (error) {
      setIsAuthenticated(false);
      setCurrentUser(null);
    } finally {
      setLoading(false);
    }
  };

  const handleLogin = async (username: string, password: string) => {
    try {
      const response = await api.admin.login(username, password);
      if (response.success && response.user) {
        setCurrentUser(response.user);
        setIsAuthenticated(true);
        localStorage.setItem('adminUser', JSON.stringify(response.user));
        showNotification('登录成功', 'success');
        return true;
      } else {
        showNotification(response.message || '登录失败', 'error');
        return false;
      }
    } catch (error) {
      showNotification('登录失败，请检查网络连接', 'error');
      return false;
    }
  };

  const handleLogout = async () => {
    try {
      await api.admin.logout();
      setIsAuthenticated(false);
      setCurrentUser(null);
      localStorage.removeItem('adminUser');
      showNotification('已退出登录', 'info');
    } catch (error) {
      console.error('Logout error:', error);
    }
  };

  const showNotification = (message: string, severity: 'success' | 'error' | 'warning' | 'info') => {
    setNotification({ open: true, message, severity });
  };

  const handleCloseNotification = () => {
    setNotification(prev => ({ ...prev, open: false }));
  };

  const drawer = (
    <div>
      {/* <Toolbar>
        <Typography variant="h6" noWrap component="div">
          管理后台
        </Typography>
      </Toolbar> */}
      <Divider />
      <List>
        {/* <ListItem disablePadding>
          <ListItemButton
            selected={location.pathname === '/admin/dashboard'}
            onClick={() => navigate('/admin/dashboard')}
          >
            <ListItemIcon>
              <DashboardIcon />
            </ListItemIcon>
            <ListItemText primary="仪表板" />
          </ListItemButton>
        </ListItem> */}
        <ListItem disablePadding>
          <ListItemButton
            selected={location.pathname === '/admin/users'}
            onClick={() => navigate('/admin/users')}
          >
            <ListItemIcon>
              <PeopleIcon />
            </ListItemIcon>
            <ListItemText primary="用户管理" />
          </ListItemButton>
        </ListItem>
        <ListItem disablePadding>
          <ListItemButton
            selected={location.pathname === '/admin/files'}
            onClick={() => navigate('/admin/files')}
          >
            <ListItemIcon>
              <FolderIcon />
            </ListItemIcon>
            <ListItemText primary="文件管理" />
          </ListItemButton>
        </ListItem>
        <ListItem disablePadding>
          <ListItemButton
            selected={location.pathname === '/admin/background'}
            onClick={() => navigate('/admin/background')}
          >
            <ListItemIcon>
              <WallpaperIcon />
            </ListItemIcon>
            <ListItemText primary="背景配置" />
          </ListItemButton>
        </ListItem>
      </List>
    </div>
  );

  if (loading) {
    return (
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <Box display="flex" justifyContent="center" alignItems="center" minHeight="100vh">
          <Typography>加载中...</Typography>
        </Box>
      </ThemeProvider>
    );
  }

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <Box sx={{ display: 'flex' }}>
        {isAuthenticated && (
          <>
            <AppBar
              position="fixed"
              sx={{
                width: { sm: `calc(100% - ${drawerWidth}px)` },
                ml: { sm: `${drawerWidth}px` },
              }}
            >
              <Toolbar>
                <IconButton
                  color="inherit"
                  aria-label="open drawer"
                  edge="start"
                  onClick={handleDrawerToggle}
                  sx={{ mr: 2, display: { sm: 'none' } }}
                >
                  <MenuIcon />
                </IconButton>
                <Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
                </Typography>
                <Typography variant="body2" sx={{ mr: 2 }}>
                  欢迎，{currentUser?.username}
                </Typography>
                <Typography 
                  variant="body2" 
                  sx={{ cursor: 'pointer', textDecoration: 'underline' }}
                  onClick={handleLogout}
                >
                  退出
                </Typography>
              </Toolbar>
            </AppBar>
            <Box
              component="nav"
              sx={{ width: { sm: drawerWidth }, flexShrink: { sm: 0 } }}
              aria-label="mailbox folders"
            >
              <Drawer
                variant="temporary"
                open={mobileOpen}
                onClose={handleDrawerToggle}
                ModalProps={{
                  keepMounted: true,
                }}
                sx={{
                  display: { xs: 'block', sm: 'none' },
                  '& .MuiDrawer-paper': { boxSizing: 'border-box', width: drawerWidth },
                }}
              >
                {drawer}
              </Drawer>
              <Drawer
                variant="permanent"
                sx={{
                  display: { xs: 'none', sm: 'block' },
                  '& .MuiDrawer-paper': { boxSizing: 'border-box', width: drawerWidth },
                }}
                open
              >
                {drawer}
              </Drawer>
            </Box>
          </>
        )}
        
        <Box
          component="main"
          sx={{
            flexGrow: 1,
            p: 3,
            width: { sm: `calc(100% - ${drawerWidth}px)` },
            ...(isAuthenticated && { mt: 8 })
          }}
        >
          <Routes>
            <Route 
              path="login" 
              element={
                !isAuthenticated ? (
                  <LoginPage onLogin={handleLogin} />
                ) : (
                  <Navigate to="/admin/users" replace />
                )
              } 
            />
            <Route 
              path="users" 
              element={
                isAuthenticated ? (
                  <UserManagement showNotification={showNotification} />
                ) : (
                  <Navigate to="/admin/login" replace />
                )
              } 
            />
            <Route 
              path="files" 
              element={
                isAuthenticated ? (
                  <FileManagement />
                ) : (
                  <Navigate to="/admin/login" replace />
                )
              } 
            />
            <Route 
              path="background" 
              element={
                isAuthenticated ? (
                  <BackgroundConfig />
                ) : (
                  <Navigate to="/admin/login" replace />
                )
              } 
            />
            <Route 
              path="/" 
              element={
                <Navigate to={isAuthenticated ? "/admin/users" : "/admin/login"} replace />
              } 
            />
          </Routes>
        </Box>
      </Box>
      
      <Snackbar
        open={notification.open}
        autoHideDuration={6000}
        onClose={handleCloseNotification}
        anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
      >
        <Alert 
          onClose={handleCloseNotification} 
          severity={notification.severity}
          sx={{ width: '100%' }}
        >
          {notification.message}
        </Alert>
      </Snackbar>
    </ThemeProvider>
  );
};

export default AdminApp;